package zuoye_4_14;

import java.util.function.IntConsumer;

public class ZeroEvenOdd {
	 private int n;
	    private int count = 1;
	    private boolean zeroFlag = true;

	    public ZeroEvenOdd(int n) {
	        this.n = n;
	    }

	    public synchronized void zero(IntConsumer printNumber) throws InterruptedException {
	        for (int i = 0; i < n; i++) {
	            while (!zeroFlag) {
	                wait();
	            }
	            printNumber.accept(0);
	            zeroFlag = false;
	            notifyAll();
	        }
	    }

	    public synchronized void even(IntConsumer printNumber) throws InterruptedException {
	        for (int i = 2; i <= n; i += 2) {
	            while (zeroFlag || (count & 1) == 1) {
	                wait();
	            }
	            printNumber.accept(i);
	            count++;
	            zeroFlag = true;
	            notifyAll();
	        }
	    }

	    public synchronized void odd(IntConsumer printNumber) throws InterruptedException {
	        for (int i = 1; i <= n; i += 2) {
	            while (zeroFlag || (count & 1) == 0) {
	                wait();
	            }
	            printNumber.accept(i);
	            count++;
	            zeroFlag = true;
	            notifyAll();
	        }
	    }
}
